package com.example.weibo3;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.example.weibo3.bean.ResultBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.transform.Result;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyFragment newInstance(String param1, String param2) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        // 逻辑代码
        EditText editText = view.findViewById(R.id.editTextid);
        EditText editTextpw = view.findViewById(R.id.editTextpw);
        CheckBox checkBox = view.findViewById(R.id.checkBox);
        Button button = view.findViewById(R.id.button2);

        // 给button添加点击事件，在事件中获取用户名、密码
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                String password = editTextpw.getText().toString();

                // http请求逻辑
                login(name, password);
            }
        });

        return view;
    }

    // 登录函数
    private void login(String name, String password) {
        // 1. 定义Map对象，组装用户名和密码 键值对
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("password", password);

        // 2. 把Map对象转成String，通过gson转
        Gson gson = new Gson();
        String jsonStr = gson.toJson(map);

        // 3. 定义RequstBody
        RequestBody requestBody = RequestBody.create(jsonStr, MediaType.parse("application/json; charset=utf-8"));

        // 4. 利用okhttp库发起http请求
        //===============网络请求================
        OkHttpClient client = new OkHttpClient();     // 初始化client对象
        // 配置参数
        Request request = new Request.Builder()
                .url("http://129.28.159.96:7001/v1/login")
                .post(requestBody)                    // 配置请求类型：post， 放入参数
                .build();
        // 发起请求
        client.newCall(request).enqueue(new Callback() {
            // 失败
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //错误处理
                Log.e("tag", e.toString());
            }

            // 成功
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                // 获取返回数据
                String data = response.body().string();   // 取出数据
                Log.i("tag", data);
                // 通过gson把字符串转成对象
                Gson gson = new Gson();
                ResultBean dataList =
                        gson.fromJson(data, new TypeToken<ResultBean>(){}.getType());
            }
        });
        //=========================================
    }
}